import { v4 } from "uuid";
import crypto from "crypto";
// import jwt from "jwt-simple";
export default function (req, res) {
  // 根据路径来自己处理数据
  if (req.path === "/user" && req.method === "POST") {
    // console.log(req.body); // 直接可以获取到解析后的请求体，不需要用户手动解析
    return res.send({ message: "ok" });
  }

  if (req.path === "/write") {
    // key = value; domain path httpOnly
    // res.setHeader("Set-Cookie", [
    //   "a=1; path=/; httpOnly=true; max-age=10; domain=localhost",
    //   "b=1; path=/; httpOnly=true; max-age=10; domain=localhost",
    // ]);
    res.setCookie("money", 50, { path: "/", signed: true });
    // /api/write  访问后 path默认会定位到 /api 下 （所有路径只要以/api开头的都可以访问这个cookie）
    return res.send("write ok");
  }

  if (req.path === "/read") {
    const val = req.getCookie("money", { signed: true });
    return res.send(val || "no found");
  }

  // 我们需要先给用户办张卡 connect.sid -
  if (req.path === "/visit") {
    if (req.session["visit"]) {
      req.session["visit"] += 1;
      return res.send(req.session["visit"] + "");
    } else {
      req.session["visit"] = 1; // setCookie
      return res.send("您是" + req.session["visit"]); // 浏览器还没有渲染，无法立刻难道cookie
    }
  }

  // if (req.path === "/visit") {
  //   let cardName = "connect.sid"; // 我开店的名字
  //   // 卡号
  //   let cardId = req.getCookie(cardName, { signed: true });
  //   // 保证卡要有，卡号也存在
  //   if (cardId && sesson[cardId]) {
  //     // 有这张卡
  //     sesson[cardId].money -= 50;
  //     return res.send("余额" + sesson[cardId].money);
  //   } else {
  //     const cardId = v4();
  //     // 开卡
  //     res.setCookie(cardName, cardId, { signed: true });
  //     // 给卡里存钱
  //     sesson[cardId] = { money: 500 };
  //     return res.send("欢迎首次光临，500元已到账");
  //   }
  // }
  // jsonwebtoken
  const jwt = {
    toBase64(data) {
      return Buffer.from(data).toString("base64url");
    },
    sign(data, secret) {
      return crypto
        .createHmac("sha256", secret)
        .update(data)
        .digest("base64url");
    },
    encode(payload, secret) {
      //
      let part1 = this.toBase64(JSON.stringify({ typ: "JWT", alg: "HS256" }));
      let part2 = this.toBase64(JSON.stringify(payload));
      let part3 = this.sign(part1 + "." + part2, secret);
      return [part1, part2, part3].join(".");
    },
    decode(token, secret) {
      let [part1, part2, oldSign] = token.split(".");
      if (this.sign(part1 + "." + part2, secret) === oldSign) {
        let { exp, ...content } = JSON.parse(
          Buffer.from(part2, "base64url").toString()
        );
        if (new Date().getTime() > new Date(exp).getTime()) {
          // 正常情况
          console.log("过期");
          throw new Error("token 过期");
        }
        return content;
      } else {
        throw new Error("token 异常");
      }
    },
  };

  if (req.path === "/login" && req.method === "POST") {
    // 签发令牌
    let { username, password } = req.body;
    // 根据用户生成token
    if (username === password) {
      // 会生成一个token
      return res.send({
        token: jwt.encode(
          {
            username,
            exp: new Date(Date.now() + 20 * 1000).toLocaleString(),
          },
          "jw"
        ),
      });
      // eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFiYyJ9.
      // O0CR2eFqhNsikeJkX0BYJVHOUpZ4Zu-wovMlUsv6H5o
      // eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFiYyJ9.O0CR2eFqhNsikeJkX0BYJVHOUpZ4Zu-wovMlUsv6H5o
    }
  }
  // 校验用户是否登录 cookie (url,header(authorization),body)
  if (req.path === "/validate") {
    // req.query['token']
    // req.headers['authorization']
    // req.body.token
    let token = req.body["token"];
    try {
      return res.send(jwt.decode(token, "jw")); // username-> abc
    } catch (e) {
      console.log(e);
      return res.send(e.toString());
    }
  }
}
